/*
 * Copyright (C) 2017 The MoonLake Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


package com.minecraft.moonlake.antistuckportal.manager;

import com.minecraft.moonlake.antistuckportal.AntiStuckPortal;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityPortalEnterEvent;
import org.bukkit.event.player.PlayerTeleportEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

public class AntiStuckPortalManager {

    private final AntiStuckPortal main;
    private final Map<String, Long> cachePortalMap;

    public AntiStuckPortalManager(AntiStuckPortal main) {
        this.main = main;
        this.cachePortalMap = new HashMap<>();
    }

    public AntiStuckPortal getMain() {
        return main;
    }

    public void close(Player player) {
        // 清除指定玩家的缓存
        if(cachePortalMap.containsKey(player.getName()))
            cachePortalMap.remove(player.getName());
    }

    public void handlerPlayerPortalEnter(EntityPortalEnterEvent event, Player player) {
        // 处理玩家进入传送门事件
        Long cache = cachePortalMap.get(player.getName());
        cachePortalMap.put(player.getName(), cache = cache != null ? ++cache : 1L);

        if(cache >= getCheckValue()) {
            // 超过值则判定为被卡地狱门则处理
            handlerAntiStuckPortal(player);
        }
    }

    public void handlerAntiStuckPortal(Player player) {
        // 处理反卡地狱门
        player.sendMessage(getMain().getMessage("AntiStuckPortalMessage"));
        player.teleport(getBackLocation(player).add(0d, 0.5d, 0d), PlayerTeleportEvent.TeleportCause.PLUGIN);
        // 清除缓存
        close(player);
    }

    public Location getBackLocation(Player player) {
        // 获取反卡地狱门的返回位置, 异常返回世界重生点
        String backLocation = getMain().getConfig().getString("BackLocation", null);

        Location finalLocation = null;
        if(backLocation == null || backLocation.isEmpty()) {
            // 如果为 null 或者为空则返回玩家当前世界的重生点
            finalLocation = player.getWorld().getSpawnLocation();
        } else {
            // 否则不为则处理
            try {
                String[] dataArray = backLocation.split(",");
                World world = Bukkit.getServer().getWorld(dataArray[0]);
                if(world == null) throw new RuntimeException("unknown world");
                double x = Double.parseDouble(dataArray[1]);
                double y = Double.parseDouble(dataArray[2]);
                double z = Double.parseDouble(dataArray[3]);
                float yaw = 0f, pitch = 0f;
                if(dataArray.length >= 6) {
                    yaw = Float.parseFloat(dataArray[4]);
                    pitch = Float.parseFloat(dataArray[5]);
                }
                // 正常则赋值
                finalLocation = new Location(world, x, y, z, yaw, pitch);
            } catch (Exception e) {
                // 异常则说明配置错误则使用世界重生点
                finalLocation = player.getWorld().getSpawnLocation();
                getMain().getLogger().log(Level.SEVERE, "错误: 处理反卡地狱门的返回位置 '" + backLocation + "' 时异常:", e);
            }
        }
        return finalLocation;
    }

    public int getCheckValue() {
        // 获取检测的值
        return getMain().getConfig().getInt("CheckValue", 1000);
    }
}
